package com.zheng.security.controller;

import com.zheng.security.service.UserService;
import com.zheng.security.utils.ApiResponse;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zyq
 * @Description
 * @createTime 2021年01月15日 14:16:00
 */
@RestController
public class MyController {

    private final UserService userService;

    public MyController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 基本测试
     * @return
     */
    @GetMapping("/test/hello")
    public ApiResponse hello(){
        return ApiResponse.success("hello security!");
    }

    /**
     * 测试角色权限 @Secured方式 角色名必须以ROLE_开头 配置类中开启securedEnabled = true
     * @return
     */
    @Secured({"ROLE_ADMIN"})
    @GetMapping("/test/role")
    public ApiResponse role(){
        return ApiResponse.success("@Secured -> hello, role!");
    }

    /**
     * 测试角色权限 @PreAuthorize方式 配置类中开启prePostEnabled = true
     * @return
     */
    @PreAuthorize("hasAnyAuthority('LOGIN')")
    @GetMapping("/test/pre/role")
    public ApiResponse preRole(){
        return ApiResponse.success("@PreAuthorize -> hello, role!");
    }


    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public ApiResponse login(@RequestParam String username, @RequestParam String password){
        return ApiResponse.success(userService.login(username, password));
    }

}
